
% Properties 
colWidCM = [85, 114, 174]/10; % in mm
% Markup properties (smaller for insets!)
fontSize = 7;
lineWidth = 0.5;
markerSize = 8;


axAspectRatio = 10.5/13;
axWidth =colWidCM(3)/4;
axHeight= colWidCM(3)/4*axAspectRatio;
exSumWidth = axWidth*0.4;



dpath = '/Users/landauland/Documents/Research/SabatiniLab/data/manuscriptPreparation/compileData';
fig6resultsMain = load(fullfile(dpath,'figure6resultsMain.mat'));
res = fig6resultsMain.res;
bswin = fig6resultsMain.bswin;
expIdx = fig6resultsMain.expIdx;
pklength = fig6resultsMain.pklength;
pyData = fig6resultsMain.pyData;
data = fig6resultsMain.data;
fig6resultsMorph = load(fullfile(dpath,'figure6resultsMorphology'));
silBranchCounter = fig6resultsMorph.silBranchCounter;
actBranchCounter = fig6resultsMorph.actBranchCounter;
fig6resultsOrder = load(fullfile(dpath,'figure6resultsOrder'));
orderRes = fig6resultsOrder.orderRes;
fig6resultsBranch = load(fullfile(dpath,'figure6resultsBranch'));
branchPointRes = fig6resultsBranch.branchPointRes;
fig6resultsConductionVelocity = load(fullfile(dpath,'figure6resultsCondVelocity'));
cvRes = fig6resultsConductionVelocity.cvRes;


pyIdxMap = [...
    2, 3, 5, nan;
    11, 12, 10, 13;
    17, 15, 16, nan;
    20, 21, nan, nan;
    22, 23, nan, nan;
    25, 26, nan, nan; 
    27, 28, nan, nan;
    35, 36, nan, nan];

lengthConstant = pyData.lengthConstant;

[~,eidx] = ismember([1 11 12],expIdx); % index of the glutamate experiments

spineList = [res(:).spine];
badList = false(numel(res),1);
badList(31)=true; % For 31, I can't reconstruct the cell accurately with the information available
mgIdx = [res(:).mg];
sidx = ~isnan(spineList) & cellfun(@(c) logical(any(c==11) && any(c==12)), {res(:).exper}, 'uni', 1);
sres = res(sidx & ~mgIdx & ~badList');

NR = numel(sres);

for nr = 1:NR
    sres(nr).branching = nan(length(lengthConstant),1);
    sres(nr).dPost = nan;
    sres(nr).dPrev = nan;
end

pyNC = size(pyIdxMap,1);
pyROI = size(pyIdxMap,2);
for pnc = 1:pyNC
    for pyr = 1:pyROI
        cidx = pyIdxMap(pnc,pyr);
        if ~isnan(cidx)
            sres(cidx).branching = pyData.result_branching(pnc,:,pyr)';
            sres(cidx).dPost = pyData.result_dPost(pnc,pyr);
            sres(cidx).dPrev = pyData.result_dPrev(pnc,pyr);
        end
    end
end

cnum = [sres(:).cellNum];
distance = [sres(:).distance]; distance(distance<0)=-25;
longestPath = [sres(:).longestPath];
totalAfter = [sres(:).totalAfter];
totalAfterPrev = [sres(:).totalAfterPrev];
distFromPrev = [sres(:).distFromPrev];
order = [sres(:).order]; order(order<0) = -3;

dPost = [sres(:).dPost];
dPrev = [sres(:).dPrev];
branching = 1000./cat(2, sres(:).branching);

tvec = 1:512;
sap = cell2mat({sres(:).sap});
sglu = cell2mat({sres(:).sglu});
sgap = cell2mat({sres(:).sgap});
ssyn = cell2mat({sres(:).ssyn});
dap = cell2mat({sres(:).dap});
dglu = cell2mat({sres(:).dglu});
dgap = cell2mat({sres(:).dgap});
dsyn = cell2mat({sres(:).dsyn});

spk = cell2mat({sres(:).spk}'); spk = spk(:,eidx);
spk(spk<0)=0;
sbase = cell2mat({sres(:).sbase}'); sbase = sbase(:,eidx); % spine Base
dpk = cell2mat({sres(:).dpk}'); dpk = dpk(:,eidx);
dpk(dpk<0)=0;
dbase = cell2mat({sres(:).dbase}'); dbase = dbase(:,eidx);

% calculate peak for synthetic
pwsyn = [100 150];
synpk = zeros(NR,1);
synpkidx = zeros(NR,1);
for s = 1:NR
    [~,synpkidx(s)] = max(ssyn(pwsyn(1):pwsyn(2),s));
    synpkidx(s) = synpkidx(s) + pwsyn(1) - 1;
    synpk(s) = mean(ssyn((0:pklength-1)+synpkidx(s),s));
end
synbase = mean(ssyn(bswin,:),1)';
synpk = synpk - synbase;

nl = spk(:,3)./synpk; 
ampreglu = (spk(:,3)-synpk)./abs(spk(:,2)); % (amplification - synthetic)/gluAlone
ampreap = (spk(:,3)-synpk)./abs(spk(:,1)); % (amplification - synthetic)/apAlone
lampreap = real(log(ampreap));

nlComponent = spk(:,3) - synpk;
exToPlot = (spk(:,1)<0.01) & (ampreglu>0.5);

argluCoeff = [distance', ones(size(distance',1),1)] \ ampreglu;
sstotARGLU = sum((ampreglu - mean(ampreglu)).^2);
ssresARGLU = sum((ampreglu - distance'*argluCoeff(1) - argluCoeff(2)).^2);
rsqARGLU = 1 - ssresARGLU/sstotARGLU;

apAmpCoeff = [spk(:,1)/max(spk(:,1)) ones(size(spk,1),1)] \ ampreglu;
sstotAPAMP = sum((ampreglu - mean(ampreglu)).^2);
ssresAPAMP = sum((ampreglu - spk(:,1)/max(spk(:,1))*apAmpCoeff(1) - apAmpCoeff(2)).^2);
rsqAPAMP = 1 - ssresAPAMP/sstotAPAMP;


uCells = unique(cnum);
NC = length(uCells);

method = 'ratiometric'; % 'threshold', or 'ratiometric'
ratioThreshold = 0.3; 

activeLimit = 0.05; % set lower bound for actives
silentLimit = 0.05; % still need to determine sample silents
distLimit = 21 * [1, 1]; % lim5t silent further, limit silent closer
ampregluLimit = 0;

numSilent = zeros(NC,1);
invalid = zeros(NC,1);
errorROI = cell(NC,1);
numCheck = cell(NC,1);
cellCount = zeros(0,1);

allSampleSilent = distance(:) > inf;
allSampleActive = distance(:) > inf;

relAmplitude = zeros(0,2);
relDistance = zeros(0,2);
relPost = zeros(0,2);
relPrev = zeros(0,2);
relBranching = zeros(0,2,length(lengthConstant));

tapSilents = [];
metaDataPairs = nan(0,7); %[CellID, SilentIdx, ActiveIdx]

for nc = 1:NC
    idxCell = cnum == uCells(nc); % idx of ROIs from this cell
    idxSilent = (dpk(:,1) <= silentLimit) & (ampreglu>ampregluLimit) & idxCell(:); % idx of silents in this cell

    listSilent = find(idxSilent);

    nSil = sum(idxSilent);
    numSilent(nc) = nSil;

    for each = 1:nSil
        % Look for active ROIs in same cell that are distance matched and
        % meet whatever criterion was set by the method
        distanceCriterion = ...
            distance(:) >= (distance(listSilent(each)) - distLimit(1)) & ...
            distance(:) <= (distance(listSilent(each)) + distLimit(2));
        
        activeCriterion = dpk(:,1) >= activeLimit; 
        
        % ROIs multiplicatively bigger than silent by ratioThreshold
        methodCriterion = dpk(listSilent(each),1)./dpk(:,1) <= ratioThreshold; 

        sampleActive = idxCell(:) & distanceCriterion & methodCriterion & activeCriterion;

        allSampleActive(sampleActive) = 1;

        numCheck{nc}{each} = sum(sampleActive);

        if any(sampleActive)
            allSampleSilent(listSilent(each))=1;
            for ii = find(sampleActive(:)')
                relAmplitude(end+1,:) = [dpk(listSilent(each),1) dpk(ii,1)];
                relDistance(end+1,:) = distance([listSilent(each), ii]);
                relPost(end+1,:) = [dPost(listSilent(each)), dPost(ii)];
                relPrev(end+1,:) = [dPrev(listSilent(each)), dPrev(ii)];
                relBranching(end+1,:,:) = permute(branching(:,[listSilent(each),ii]),[3 2 1]);
                tapSilents(end+1) = totalAfterPrev(listSilent(each));
            end
            cellCount(end+1) = nc;
            cmeta = [uCells(nc), listSilent(each), find(sampleActive(:)')];
            metaDataPairs(end+1,1:length(cmeta)) = cmeta;
        end
    end
end
cellNs = length(unique(cellCount));


mzpsize = [482 1106];
mzpHeight = 3.4;
mzpFigureWidth = mzpHeight * mzpsize(2)/mzpsize(1);

close all

% Figure 6B
idxExSil = 11; 
idxExAct = 12;
option = 1;
exTraceWidth = 2.2;
figure(1); clf; hold on; 
set(gcf,'units','centimeters','position',[30 30 exTraceWidth mzpHeight]);
set(gca,'units','centimeters','position',[0.15 0 exTraceWidth*0.91 mzpHeight*0.95]); % 0.91

plot(tvec, dap(:,idxExAct) - dbase(idxExAct,1), 'color','k','linewidth',lineWidth);
plot(tvec, dap(:,idxExSil) - dbase(idxExSil,1), 'color','b','linewidth',lineWidth);
xlim([51 400]);
ylim([-0.06 0.18]);
% Mark AP Time
line([100 100],[-0.0475 -0.03],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [330 0.105 50 0.03];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),[sprintf('%d%%',100*scalePosition(4)),' \DeltaG/R'],'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6C
setBackX = [-0.1 -0.15 -0.2 -0.5];
xPos = [0.1, 0.5];
figure(2); clf; hold on;
set(gcf,'units','centimeters','position',[35 30 exSumWidth mzpHeight]);
set(gca,'units','centimeters','position',[0.8 0.2 exSumWidth*0.92 mzpHeight*0.9]);
for i = 1:size(relAmplitude,1)
    plot(xPos([2 1]),relAmplitude(i,:),'color','k','linewidth',lineWidth,'marker','.','markersize',markerSize);
end
plot(xPos(2), relAmplitude(:,1), 'color','b','marker','.','markersize',markerSize,'linestyle','none');
xLim = [0 1.5];
xlim(xLim + [setBackX(2),0]);
ylim([0 0.2]);
line(xLim(1)+setBackX([1,1]),[0 10],'color','k','linewidth',lineWidth);
yticks = 0:0.1:0.2;
for yt = yticks
    line(xLim(1)+setBackX([2 1]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(xLim(1)+setBackX(3),yt,num2str(yt),'fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackX(4),0.1,'\DeltaCa_{AP}  (\DeltaG/R)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6D
setBackX = [-0.1 -0.15 -0.2 -0.65];
xPos = [0.1, 0.5];
figure(11); clf; hold on;
set(gcf,'units','centimeters','position',[40 30 exSumWidth mzpHeight]);
set(gca,'units','centimeters','position',[0.8 0.2 exSumWidth*0.92 mzpHeight*0.9]);
for i = 1:size(relDistance,1)
    plot(xPos([2 1]),relDistance(i,:),'color','k','linewidth',lineWidth,'marker','.','markersize',markerSize);
end
plot(xPos(2), relDistance(:,1), 'color','b','marker','.','markersize',markerSize,'linestyle','none');
xLim = [0 1.5];
xlim(xLim + [setBackX(2),0]);
ylim([0 225]);
line(xLim(1)+setBackX([1,1]),[0 210],'color','k','linewidth',lineWidth);
yticks = 0:100:200;
for yt = yticks
    line(xLim(1)+setBackX([2 1]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(xLim(1)+setBackX(3),yt,num2str(yt),'fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackX(4),112.5,'Distance (µm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6E
setBackX = [-0.1 -0.15 -0.18 -0.6];
xPos = [0.1,0.5];
idxLambda = find(lengthConstant==145);
figure(3); clf; hold on;
set(gcf,'units','centimeters','position',[45 30 exSumWidth mzpHeight]);
set(gca,'units','centimeters','position',[0.75 0.2 exSumWidth*0.92 mzpHeight*0.9]);
plot(xPos([2 1]),1./relBranching(:,:,idxLambda),'color','k','linewidth',lineWidth,'marker','.','markersize',markerSize);
plot(xPos(2), 1./relBranching(:,1,idxLambda), 'color','b','marker','.','markersize',markerSize,'linestyle','none');
xLim = [0 1.5];
xlim(xLim+[setBackX(2),0]);
ylim([0 1]);
line(xLim(1)+setBackX([1,1]),[0 10],'color','k','linewidth',lineWidth);
yticks = 0:0.25:1;
for yt = yticks
    line(xLim(1)+setBackX([2 1]),yt*[1,1],'color','k','linewidth',lineWidth);
    if rem(yt,0.5)~=0, continue, end
    text(xLim(1)+setBackX(3),yt,num2str(yt),'fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackX(4),0.5,'Branch Complexity (mm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


setBackX = [-0.1 -0.15 -0.2 -0.4];
figure(4); clf; hold on;
set(gcf,'units','centimeters','position',[40 20 exSumWidth axHeight]);
set(gca,'units','centimeters','position',[0.2 0.2 exSumWidth*0.92 axHeight*0.9]);
xlim([0 10]);
ylim([0 18]);
text(0.5,3,'High \DeltaCa_{AP}','Fontsize',fontSize,'HorizontalAlignment','Left');
text(0.5,1,'Low\DeltaCa_{AP}','Fontsize',fontSize,'HorizontalAlignment','Left');
plot(0,3.3,'color','k','marker','.','markersize',markerSize);
plot(0,1.3,'color','b','marker','.','markersize',markerSize);
set(gca,'visible','off');


% Figure 6F
idxROI = data.matIdxROI;
idxActFit = idxROI~=0;
idxROI_ActFit = idxROI(idxActFit);
iresActFit = data.matIres(idxActFit,:);
cellID_ActFit = data.matCellID(idxActFit);
cutExp_ActFit = data.matCutExp(idxActFit);
numFits = size(iresActFit, 1)/2;
exIres = zeros(2,numFits,2);
exIres(1,:,1) = iresActFit(cutExp_ActFit==0,1);
exIres(1,:,2) = iresActFit(cutExp_ActFit==1,1);
idxNoCut = find(cutExp_ActFit==0);
idxCutExp = find(cutExp_ActFit);
for nf = 1:numFits
    exIres(2,nf,1) = iresActFit(idxNoCut(nf),idxROI_ActFit(idxNoCut(nf))+1);
end
for nf = 1:numFits
    exIres(2,nf,2) = iresActFit(idxCutExp(nf),idxROI_ActFit(idxCutExp(nf))+1);
end
setBackX = [-0.1 -0.15 -0.2 -0.7];
figure(5); clf; hold on;
set(gcf,'units','centimeters','position',[50 30 exSumWidth mzpHeight]);
set(gca,'units','centimeters','position',[0.85 0.2 exSumWidth*0.92 mzpHeight*0.9]);
plot(xPos([2,1]),exIres(:,:,1),'color','k','linewidth',lineWidth,'marker','.','markersize',markerSize);
plot(xPos(2),exIres(1,:,1),'color','b','marker','.','markersize',markerSize,'linestyle','none');
xLim = [0 1.5];
xlim(xLim+[setBackX(2),0]);
ylim([0 400]);
line(xLim(1)+setBackX([1,1]),[0 400],'color','k','linewidth',lineWidth);
yticks = 0:100:400;
for yt = yticks
    line(xLim(1)+setBackX([2 1]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(xLim(1)+setBackX(3),yt,num2str(yt),'fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackX(4),200,'Input Resistance (M\Omega)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6G
conflateDP = false;
maxDistance = 520;
dxDist = 1;
binMax = ceil(maxDistance/dxDist)*dxDist;
binEdges = -binMax*(~conflateDP):dxDist:binMax;
binCenters = mean([binEdges(1:end-1); binEdges(2:end)]);
numBins = length(binEdges)-1;
morphFigureWidth = 2.76;
morphFigureHeight = 4.935;
setBackX = [-0.3 -0.45 -0.6 -2.8];
setBackY = [-8 -13 -9 -51];
smsm = 1;
scaleFactor = [sqrt(size(silBranchCounter,2)) sqrt(size(actBranchCounter,2))];
figure(6); clf; hold on;
set(gcf,'units','centimeters','position',[55 30 morphFigureWidth morphFigureHeight]);
set(gca,'units','centimeters','position',[0.86 0.55 morphFigureWidth*0.65 morphFigureHeight*0.86]);
plot(mean(smoothsmooth(silBranchCounter,smsm),2), binCenters, 'color','b','linewidth',lineWidth);
plot(mean(smoothsmooth(actBranchCounter,smsm),2), binCenters, 'color','k','linewidth',lineWidth);
xSilPatchCenter = [mean(smoothsmooth(silBranchCounter,smsm),2); flipud(mean(smoothsmooth(silBranchCounter,smsm),2))];
xSilError = [std(smoothsmooth(silBranchCounter,smsm),1,2)/scaleFactor(1); -flipud(std(smoothsmooth(silBranchCounter,smsm),1,2)/scaleFactor(1))];
xActPatchCenter = [mean(smoothsmooth(actBranchCounter,smsm),2); flipud(mean(smoothsmooth(actBranchCounter,smsm),2))];
xActError = [std(smoothsmooth(actBranchCounter,smsm),1,2)/scaleFactor(2); -flipud(std(smoothsmooth(actBranchCounter,smsm),1,2)/scaleFactor(2))];
yPatchCenter = [binCenters, fliplr(binCenters)];
patch(xSilPatchCenter+xSilError,yPatchCenter,'b','FaceColor','b','FaceAlpha',0.1,'EdgeColor','none');
patch(xActPatchCenter+xActError,yPatchCenter,'k','FaceColor','k','FaceAlpha',0.1,'EdgeColor','none');
line([0 7.25],[0 0],'color','k','linewidth',lineWidth,'linestyle','--');
yLim = 200*[-2.6*(~conflateDP) 1];
xlim([setBackX(2) 7]);
ylim(yLim + [setBackY(2),0]);
line([0 7.25],(yLim(1)+setBackY(1))*[1,1],'color','k','linewidth',lineWidth);
line(setBackX([1,1]),[200*-2.6 yLim(2)],'color','k','linewidth',lineWidth);
xticks = 0:2:6;
for xt = xticks
    line([xt,xt],yLim(1)+[setBackY(2) setBackY(1)],'color','k','linewidth',lineWidth);
    text(xt,yLim(1)+setBackY(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(3.5,yLim(1)+setBackY(4),'# Branches','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = -400:200:200;
for yt = yticks
    line(setBackX([2,1]),[yt,yt],'color','k','linewidth',lineWidth);
    text(setBackX(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackX(4),yLim(1)+diff(yLim)/2,'Distance from ROI (µm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
% Make Legend
legPos = [0.75 0.6 0.2, -440, -48, 5];
text(sum(legPos(1:3)),legPos(4),'High \DeltaCa_{AP}','Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Middle');
text(sum(legPos(1:3)),sum(legPos(4:5)),'Low \DeltaCa_{AP}','Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Middle');
line(legPos(1)+[0,legPos(2)],sum(legPos([4,6]))*[1,1],'color','k','linewidth',lineWidth);
line(legPos(1)+[0,legPos(2)],sum(legPos(4:6))*[1,1],'color','b','linewidth',lineWidth);
text(-1.75,20,'dist >','Fontsize',fontSize,'HorizontalAlignment','Left','Rotation',90);
text(-1.75,-20,'< prox','Fontsize',fontSize,'HorizontalAlignment','Right','Rotation',90);
set(gca,'visible','off');



%% -- Figure 6 - figure supplement 1

close all

axWidth = colWidCM(1)/2;
axHeight= 3.1; % using similar as in Figure 2...

% Figure 6 - figure supplement 1B(top)
exCloseWithin = 63; % 191023b - distance: 99, 145
exFarAcross = 120; % 210525a - distance: 74, 122

figure(1); clf; hold on;
set(gcf,'units','centimeters','position',[47 35 axWidth axHeight/2]);
set(gca,'units','centimeters','position',[0.2 0.1 axWidth*0.9 axHeight/2*0.9]); % Note difference for equal axes!
plot(1:512, branchPointRes(exCloseWithin).dap(:,1) - mean(branchPointRes(exCloseWithin).dap(80:98,1)), 'color','k','linewidth',lineWidth);
plot(1:512, branchPointRes(exCloseWithin).dap(:,2) - mean(branchPointRes(exCloseWithin).dap(80:98,2)), 'color','b','linewidth',lineWidth);
xlim([50 450]);
ylim([-0.03 0.185]);
% Mark AP Time
line([100 100],[-0.029 -0.017],'color','k','linewidth',lineWidth);
% Create Legend
legPosition = [420 450 0.16 0.12 -10];
line(legPosition([1,2]),legPosition(3)*[1,1],'color','k','linewidth',lineWidth);
line(legPosition([1,2]),legPosition(4)*[1,1],'color','k','linewidth',lineWidth);
text(legPosition(1)+legPosition(5),legPosition(3),'proximal','Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
text(legPosition(1)+legPosition(5),legPosition(4),'distal','Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
set(gca,'visible','off');

% Figure 6 - figure supplement 1B(bottom)
figure(2); clf; hold on; 
set(gcf,'units','centimeters','position',[47 30 axWidth axHeight/2]);
set(gca,'units','centimeters','position',[0.2 0.1 axWidth*0.9 axHeight/2*0.9]); % Note difference for equal axes!
plot(1:512, branchPointRes(exFarAcross).dap(:,1) - mean(branchPointRes(exFarAcross).dap(80:98,1)), 'color','k','linewidth',lineWidth);
plot(1:512, branchPointRes(exFarAcross).dap(:,2) - mean(branchPointRes(exFarAcross).dap(80:98,2)), 'color','b','linewidth',lineWidth);
xlim([50 450]);
ylim([-0.03 0.185]);
% Mark AP Time
line([100 100],[-0.029 -0.017],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [370 0.11 50 0.05];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),[sprintf('%d%%',100*scalePosition(4)),' \DeltaG/R'],'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6 - figure supplement 1C
distance = cat(1, branchPointRes(:).distance);
distIdx = distance(:,1) > 0; % Condition distances!!!
NP = sum(distIdx); 
distance = distance(distIdx,:);
dpk = cat(1, branchPointRes(distIdx).dpk);
dpk(dpk<0.001) = 0.001;
branch = [branchPointRes(distIdx).branchPoint];
idxSameBranch = (branch==0);
diffDist = distance(:,2) - distance(:,1);
diffPeak = dpk(:,2) - dpk(:,1); 
ratioPeak = (dpk(:,1) - dpk(:,2)) ./ dpk(:,1);
idxBigFirst = dpk(:,1) > 0.1;
idxFarEnough = distance(:,1); 
idxWithin = branch==0;
thing2plot = dpk(:,2)./dpk(:,1); 
figure(3); clf; hold on; 
set(gcf,'units','centimeters','position',[42 23 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.7 0.4 axWidth*0.8 axHeight*0.85]); % Note difference for equal axes!
distributionPlot({thing2plot(idxBigFirst & idxFarEnough & idxWithin'),thing2plot(idxBigFirst & idxFarEnough & ~idxWithin')},'xvalue',1:2,'support',[0 3],'bandwidth',0.6,'showMM',0,'globalNorm',1);
plot(0.75,thing2plot(idxBigFirst & idxFarEnough & idxWithin'),'linestyle','none','marker','o','color','k','markersize',markerSize/2);
plot(1.45,thing2plot(idxBigFirst & idxFarEnough & ~idxWithin'),'linestyle','none','marker','o','color','k','markersize',markerSize/2);
xlim([0.45 2.5]);
ylim([0 2.4]);
line([0.5 0.5],[0, 2.35],'color','k','linewidth',lineWidth);
yts = 0:2;
for yt = yts
    line([0.45 0.5],[yt,yt],'color','k','linewidth',lineWidth);
    text(0.4,yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(1,-0.03,'Within','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
text(2,-0.03,'Across','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
text(0.25,1.2,'Ratio \DeltaG/R (d/p)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');



% Figure 6 - figure supplement 1D
orderDPK = cellfun(@(c) c(1), {orderRes(:).dpk},'uni', 1);
orderOrder = [orderRes(:).order];
orderDistance = [orderRes(:).distance];
idxGood = orderDistance > 0 & orderOrder >= 0; 
orderDpk = orderDPK(idxGood);
orderDistance = orderDistance(idxGood);
orderOrder = orderOrder(idxGood);

numInOrder = numel(orderDpk);
regLine = [ones(numInOrder,1),orderDpk(:)] \ orderOrder(:);

setBackX = [-0.03 -0.035, -0.04, -0.085];
setBackY = -0.04+[-0.4 -0.525 -0.45, -1.6];
figure(4); clf; hold on; 
set(gcf,'units','centimeters','position',[47 23 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.45 0.65 axWidth*0.85 axHeight*0.75]); % Note difference for equal axes!

plot(orderDpk,orderOrder,'color','k','linestyle','none','marker','.','markersize',markerSize);
xlim([setBackX(2) 0.47]);
ylim([setBackY(2) 11]);
line([0 0.47],[setBackY(1) setBackY(1)],'color','k','linewidth',lineWidth);
line([setBackX(1) setBackX(1)],[0 11],'color','k','linewidth',lineWidth);
xticks = 0:0.2:0.4;
for xt = xticks
    line([xt,xt],[setBackY(2) setBackY(1)],'color','k','linewidth',lineWidth);
    text(xt,setBackY(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(0.235,setBackY(4),'\DeltaCa_{AP}','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:4:10;
for yt = yticks
    line([setBackX(2) setBackX(1)],[yt,yt],'color','k','linewidth',lineWidth);
    text(setBackX(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackX(4),11/2,'Branch Order','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Middle','Rotation',90);
set(gca,'visible','off');





%% -- Figure 6 - figure supplement 3

close all

saxWidth =colWidCM(3)/4;
saxHeight= colWidCM(3)/4*axAspectRatio;


mainIdx = find(lengthConstant==145);
iresLoaded = exIres(:,:,1)';
NLC = length(lengthConstant);
r2 = zeros(1,NLC);
for nlc = 1:NLC
    cload = relBranching(:,:,nlc);
    cmdl = fitlm(cload(:),iresLoaded(:));
    r2(nlc) = cmdl.Rsquared.Ordinary;
end

% Figure 6 - figure supplement 3A
setBackX = [-0.07 -0.12 -0.11 -0.21]/2*350;
setBackY = [-0.013 -0.022 -0.026 -0.095]/0.45*4;
figure(1); clf; hold on; 
set(gcf,'units','centimeters','position',[40 30 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.85 0.56 saxWidth*0.75 saxHeight*0.82]);
cxcx = relBranching(:,:,mainIdx);
plot(cxcx(:),iresLoaded(:),'color','k','marker','.','markersize',markerSize,'linestyle','none');
xlim([setBackY(2) 4]);
ylim([setBackX(2) 350]);
line([0 10],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 350],'color','k','linewidth',lineWidth);
xticks = 0:1:4;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(2, setBackX(4), '1/Branch Complexity (mm^{-1})','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:100:300;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), 175, 'Input Resistance (M\Omega)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');

% Figure 6 - figure supplement 3B
setBackX = [-0.07 -0.12 -0.11 -0.26]/2*1;
setBackY = [-0.013 -0.022 -0.026 -0.08]/0.45*400;
figure(2); clf; hold on; 
set(gcf,'units','centimeters','position',[45 30 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.75 0.56 saxWidth*0.75 saxHeight*0.82]);
plot(lengthConstant,r2,'color','k','linewidth',lineWidth/2,'marker','.','markersize',markerSize-4)
plot(lengthConstant(mainIdx),r2(mainIdx),'color','r','marker','.','markersize',markerSize-2)
xlim([setBackY(2) 400]);
ylim([setBackX(2) 1]);
line([0 400],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 1],'color','k','linewidth',lineWidth);
xticks = 0:100:400;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(200, setBackX(4), 'Length Constant (µm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.5:1;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), 0.5, 'R^2 w/ Input Resistance','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6 - figure supplement 3C
setBackX = [-0.07 -0.12 -0.11 -0.26]/2*1.25;
setBackY = [-0.013 -0.022 -0.026 -0.09]/0.45*400;
figure(3); clf; hold on; 
set(gcf,'units','centimeters','position',[50 30 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.85 0.56 saxWidth*0.74 saxHeight*0.82]);
shadedErrorBar(lengthConstant,mean(1./squeeze(relBranching(:,2,:)),1),std(1./squeeze(relBranching(:,2,:)),1,1),{'color','k','linewidth',lineWidth/2,'marker','.','markersize',markerSize-4});
shadedErrorBar(lengthConstant,mean(1./squeeze(relBranching(:,1,:)),1),std(1./squeeze(relBranching(:,1,:)),1,1),{'color','b','linewidth',lineWidth/2,'marker','.','markersize',markerSize-4});
line([145 145],[0,1],'color','r','linewidth',lineWidth,'linestyle',':');
xlim([setBackY(2) 400]);
ylim([setBackX(2) 1.25]);
line([0 400],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 1.25],'color','k','linewidth',lineWidth);
xticks = 0:100:400;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(200, setBackX(4), 'Length Constant (µm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.5:1;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), 1.25/2, 'Electrotonic Load (mm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
% Legend
legPos = [400 -30 -10 0.25 -0.18];
%legPos = [10 30 10 1.2 -0.2];
line(legPos(1)+[0 legPos(2)],legPos([4,4])+0*legPos(5),'color','k','linewidth',lineWidth);
line(legPos(1)+[0 legPos(2)],legPos([4,4])+1*legPos(5),'color','b','linewidth',lineWidth);
text(sum(legPos(1:3)),legPos(4)+0*legPos(5),'High \DeltaCa_{AP}','Fontsize',fontSize,'horizontalAlignment','Right');
text(sum(legPos(1:3)),legPos(4)+1*legPos(5),'Low \DeltaCa_{AP}','Fontsize',fontSize,'horizontalAlignment','Right');
set(gca,'visible','off');





%% ======== conduction velocity ===============

close all

colWidCM = [85, 114, 174]/10; % in mm
% Markup properties (smaller for insets!)
fontSize = 7;
lineWidth = 0.5;
markerSize = 8;

axAspectRatio = 10.5/13;
axWidth =colWidCM(3)/4;
axHeight= colWidCM(3)/4*axAspectRatio;
exSumWidth = axWidth*0.4;

saxWidth =colWidCM(3)/4;
saxHeight= colWidCM(3)/4*axAspectRatio;


cellNum = [cvRes(:).cellNum];


% -- do analysis --
% Get some meta data
NR = numel(cvRes); % just to make sure it's here
rDist = [cvRes(:).distance];
expID = [cvRes(:).expID];

% Filtering/Derivative/Summary - Parameters
h = 3; % used to be 6
dsfactor = 16;
boxcarKernel = 5;
apSmoothing = 20;

% Timing 
dt = 512/4000;
tv = dt:dt:512;
psdt = dt/16;
pstv = psdt:psdt:512;
physdt = 0.01;
phystv = physdt:physdt:1000; % (known)

% ------ Adjust for AP Jitter ------ 
apMaxWin = [find(pstv>=100,1) find(pstv>=105,1)];
allPhys = {cvRes(:).phys};
smoothPhys = cellfun(@(c) smoothsmooth(c,apSmoothing), allPhys, 'uni', 0);
usphys = cellfun(@(c) interp1(phystv',c,pstv), smoothPhys, 'uni', 0);

% Get index of max AP voltage
apPt = cell(1,NR);
apTime = cell(1,NR);
for r = 1:NR
    [~,apPt{r}] = max(usphys{r}(apMaxWin(1):apMaxWin(2),:),[],1);
    apPt{r} = apPt{r} + apMaxWin(1) - 1;
    apTime{r} = pstv(apPt{r});
end

zpt = find(pstv>=100,1); % we're going to shift it so the peak of the AP is at 100ms
japhys = cell(1,NR);
jadata = cell(1,NR);
allData = cellfun(@double, {cvRes(:).gtif}, 'uni', 0); % Full dataset
for r = 1:NR
    cphys = usphys{r};
    cdata = allData{r};
    NA = size(cdata,2);
    cjaphys = zeros(size(cphys));
    cjadata = zeros(size(cdata));
    for a = 1:NA
        cp = nanshift(cphys(:,a),zpt - apPt{r}(a));
        cc = nanshift(cdata(:,a),zpt - apPt{r}(a));
        idxnan = find(isnan(cc));
        cp(idxnan) = mean(cp(idxnan(1)-101:idxnan(1)-1));
        cc(idxnan) = mean(cc(idxnan(1)-101:idxnan(1)-1));
        cjaphys(:,a) = cp;
        cjadata(:,a) = cc;
    end
    japhys{r} = cjaphys; % current jitter adjusted phys
    jadata{r} = cjadata; % current jitter adjusted data
end

% ------- down-sample / base-subtract / normalize / filter ------------
ds = cellfun(@(c) dsarray(c, dsfactor), jadata, 'uni', 0);

stBase = find(tv>=78,1);
enBase = find(tv>=98,1);
dsbase = cellfun(@(c) c - repmat(mean(c(stBase:enBase,:),1),size(c,1),1), ds, 'uni', 0);

pkwin = [find(tv>=98,1) find(tv>=115,1)];
pkidx = zeros(1,NR);
pks = cell(1,NR);
for r = 1:NR
    cmean = mean(dsbase{r},2);
    [~,pkidx(r)] = max(cmean(pkwin(1):pkwin(2)));
    pkidx(r) = pkidx(r) + pkwin(1) - 1;
    pks{r} = mean(cmean(pkidx(r):pkidx(r) + round(10/dt)),1);
end
dsnorm = cellfun(@(d,p) d./repmat(p,size(d,1),size(d,2)),dsbase, pks, 'uni', 0);
fdata = cellfun(@(c) smoothsmooth(c, boxcarKernel), dsnorm, 'uni', 0);


% ------- derivative, mean ----------
mdata = cell2mat(cellfun(@(c) mean(c,2), fdata, 'uni', 0));
mphys = cell2mat(cellfun(@(c) mean(c,2), japhys, 'uni', 0));


% ------- fwhm, conduction delay -------
fptv = tv(1+2*h:end-2*h);
fpca = fivePointDer(mdata,h);
deconv = zeros(size(mdata));
eps = 0.05;
ft = fittype('a*exp(-x/tau)');
fo = fitoptions(ft);
fo.Upper = [1 1000];
fo.Lower = [0 0];
fo.Start = [1 150];
startFit = find(tv>=120,1);
ftime = tv(startFit:end) - tv(startFit);
for s = 1:size(mdata,2)
    fitdata = mdata(startFit:end,s);
    fitdata = fitdata./mean(fitdata(1:20));
    cfit = fit(ftime(:),fitdata(:),ft,fo);
    kerneldata = exp(-tv(:)/cfit.tau);
    kernelY = fft(kerneldata);
    dataY = fft(mdata(:,s));
    deconvY = dataY.*conj(kernelY) ./ (kernelY.*conj(kernelY) + eps*mean(kernelY.*conj(kernelY)));
    deconv(:,s) = real(ifft(deconvY));
end    

% ------ AP analysis --------
apFPD = 25;
phys2Der = fivePointDer(fivePointDer(mphys,apFPD),apFPD);
[~,idxApKink] = max(phys2Der);

kinkAmplitude = zeros(size(mphys,2),1);
for ns = 1:size(mphys,2)
    kinkAmplitude(ns) = mphys(idxApKink(ns)+4*apFPD,ns);
end
idxKinkGood = kinkAmplitude <= -40; 



% -- do some shifting to move around the imaging derivative data to kink --
h = 50;
fptv = tv(1+2*h:end-2*h);
fpca = fivePointDer(smoothsmooth(mdata,10),h);

idxApPeak = find(pstv==100);

% -- to-do list: upsample fpca, shift it to adjust for the kink-phys trace
ustv = tv(1):psdt:tv(end);
usfptv = ustv(1+2*h:end-2*h);
kaca = zeros(length(ustv), size(mdata,2));
kafpca = zeros(length(usfptv),size(mdata,2));
for r = 1:NR
    cdata = mdata(:,r);
    cusdata = interp1(tv,cdata,tv(1):psdt:tv(end));
    ckadata = nanshift(cusdata,idxApPeak-(idxApKink(ns)+4*apFPD));
    kaca(:,r) = ckadata;
    kafpca(:,r) = fivePointDer(ckadata',h);
end

dwin = [find(usfptv>=100,1,'first') find(usfptv>=105,1,'first')];
[dpk,dpkt] = max(kafpca(dwin(1):dwin(2),:),[],1);
dpkt = dpkt + dwin(1) - 1;
dpkTimes = usfptv(dpkt);

apBottom = -30;
fwhmCa = zeros(1,size(kafpca,2));
fwhmAp = zeros(1,size(mphys,2));
for s = 1:size(kafpca,2)
    fHalfPt = find(kafpca(dpkt(s):-1:1,s) <= dpk(s)/2,1,'first');
    sHalfPt = find(kafpca(dpkt(s):end,s) <= dpk(s)/2,1,'first');
    fwhmCa(s) = (sHalfPt + fHalfPt) * dt;
    
    cvmRest = mean(mphys(find(pstv>=50,1):find(pstv>=70,1),s));
    cvmPeak = mphys(idxApPeak,s);
    cvmHalf = mean([cvmRest,cvmPeak]);
    fHalfPt = find(mphys(idxApPeak:-1:1,s) <= apBottom,1,'first'); % or apBottom instead of cvmHalf....
    sHalfPt = find(mphys(idxApPeak:end,s) <= apBottom,1,'first');
    fwhmAp(s) = (sHalfPt + fHalfPt) * psdt;
end

idx2use = ~isnan(rDist);
idx2use((mdata(find(tv>=102.5,1),~isnan(rDist))<0.8))=false;


kinkAdjustedPhys = zeros(size(mphys));
for ns = 1:size(mphys,2)
    kinkAdjustedPhys(:,ns) = nanshift(mphys(:,ns),idxApPeak-(idxApKink(ns)+4*apFPD));
end
idxKinkGood(kinkAdjustedPhys(find(pstv>=101.8,1),:)>-25)=false;
xLim = [99 104];
yLim = [-88 45];
setBackX = [-0.07 -0.12 -0.11 -0.27]/2*diff(yLim) + yLim(1);
setBackY = [-0.013 -0.022 -0.026 -0.0825]/0.45*diff(xLim) + xLim(1);
xUse = find(pstv>=xLim(1)+0.1,1):find(pstv>=xLim(2),1);




% Figure 6 - figure supplement 1B
idxExample = 20;
xLim = [50 300]-100;
yLim = [0.5 10.5];
setBackX = [-0.07 -0.15 -0.012 -0.3]/2*diff(yLim) + yLim(1);
setBackY = [-0.013 -0.022 -0.01 -0.05]/0.45*diff(xLim) + xLim(1);
figure(2); clf; 
set(gcf,'units','centimeters','position',[35 35 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.62 0.56 saxWidth*0.77 saxHeight*0.68]);
hold on; 
imagesc(tv-100,1:size(dsnorm{idxExample},2),dsnorm{idxExample}')
xlim(xLim);
ylim(yLim);
colormap('hot')
caxis([0 3]);
xticks = 0:100:200;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(175-100, setBackX(4), 'Time (ms)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 2:2:10;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), mean(yLim), 'Trial #','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6 - figure supplement 1C
xLim = [50 300]-100;
yLim = [-0.5 2.4];
setBackX = [-0.07 -0.12 -0.11 -0.42]/2*diff(yLim) + yLim(1);
setBackY = [-0.013 -0.022 -0.029 -0.06]/0.45*diff(xLim) + xLim(1);
xUse = find(tv>=50,1):find(tv>=300,1);
stBase = find(tv>=78,1);
enBase = find(tv>=98,1);
baselineExample = mean(ds{idxExample}(stBase:enBase,:),'all');
figure(3); clf; hold on;
set(gcf,'units','centimeters','position',[35 30 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.62 0.56 saxWidth*0.77 saxHeight*0.68]);
plot(tv(xUse)-100, (mean(ds{idxExample}(xUse,:),2)-baselineExample)/baselineExample, 'color','k','linewidth',lineWidth);
xlim([setBackY(2) xLim(2)]);
ylim([setBackX(2) yLim(2)]);
line(setBackY([1,1]),yLim,'color','k','linewidth',lineWidth);
line(xLim,setBackX([1,1]),'color','k','linewidth',lineWidth);
xticks = 0:100:200;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(175-100, setBackX(4), 'Time (ms)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:2;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), mean(yLim), '\DeltaF/F','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');





saxHeight = 2.5149;
xLim = [99.5 103.5];
xFluorUse = find(ustv>=xLim(1)+0.1,1):find(ustv>=xLim(2),1);
yLim = [-0.1 1.2];
setBackX = [-0.07 -0.12 -0.11 -0.42]/2*diff(yLim) + yLim(1);
setBackY = [-0.013 -0.022 -0.026 -0.0425]/0.45*diff(xLim) + xLim(1);
idxFluor2Use = false(1,length(cellNum));
idxFluor2Use([19,20]) = true; 
colorRoi = [0,0,0; 0,0.65,0];
idxRoi = [19,20];


% Figure 6 - figure supplement 1E
figure(5); clf; hold on;
set(gcf,'units','centimeters','position',[50 35 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.62 0.56 saxWidth*0.77 saxHeight*0.68]);
for i = 1:length(idxRoi)
    idx = idxRoi(i);
    idxcmap = round(rDist(idx));
    cThing2Plot = smoothsmooth(kaca,2);
    plot(ustv(xFluorUse), cThing2Plot(xFluorUse,idx),'color',colorRoi(i,:),'linewidth',lineWidth);
end
xlim([setBackY(2) xLim(2)]);
ylim([setBackX(2) yLim(2)]);
line(setBackY([1,1]),yLim,'color','k','linewidth',lineWidth);
line(xLim,setBackX([1,1]),'color','k','linewidth',lineWidth);
xticks = 100:103;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt-100),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(101.5, setBackX(4), 'Time (ms)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.5:1;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
end
text(setBackY(4), mean(yLim), '\DeltaF (AU)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
legPos = [99.57, 0.32, 0.05, 1.03, -0.24];
line(legPos(1) + [0 legPos(2)], (legPos(4)+0*legPos(5))*[1,1],'color','k','linewidth',lineWidth);
line(legPos(1) + [0 legPos(2)], (legPos(4)+1*legPos(5))*[1,1],'color',[0,0.65,0],'linewidth',lineWidth);
text(sum(legPos(1:3)),(legPos(4)+0*legPos(5)),'73 µm','Fontsize',fontSize,'horizontalAlignment','Left','VerticalAlignment','Middle');
text(sum(legPos(1:3)),(legPos(4)+1*legPos(5)),'111 µm','Fontsize',fontSize,'horizontalAlignment','Left','VerticalAlignment','Middle');
set(gca,'visible','off');


% Figure 6 - figure supplement 1F
yLim = [-80 40];
setBackX = [-0.07 -0.12 -0.11 -0.42]/2*diff(yLim) + yLim(1);
setBackY = [-0.013 -0.022 -0.026 -0.075]/0.45*diff(xLim) + xLim(1);
xPhysUse = find(pstv>=xLim(1)+0.1,1):find(pstv>=xLim(2),1);
figure(6); clf; hold on; 
set(gcf,'units','centimeters','position',[50 30 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.62 0.56 saxWidth*0.77 saxHeight*0.68]);
plot(pstv(xPhysUse),kinkAdjustedPhys(xPhysUse, idxRoi(1)),'color','k','linewidth',lineWidth);
xlim([setBackY(2) xLim(2)]);
ylim([setBackX(2) yLim(2)]);
line(setBackY([1,1]),yLim,'color','k','linewidth',lineWidth);
line(xLim,setBackX([1,1]),'color','k','linewidth',lineWidth);
xticks = 100:103;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt-100),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(101.5, setBackX(4), 'Time (ms)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = -80:40:40;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), mean(yLim), 'mV','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');



% Figure 6 - figure supplement 1G
cmap = cat(2, zeros(125,1), linspace(0,1,125)', zeros(125,1));
xLim = [99 104];
xUse = find(usfptv>=xLim(1)+0.1,1):find(usfptv>=xLim(2),1);
yLim = [-6 26];
setBackX = [-0.07 -0.12 -0.11 -0.27]/2*diff(yLim) + yLim(1);
setBackY = [-0.013 -0.022 -0.026 -0.0425]/0.45*diff(xLim) + xLim(1);
figure(7); clf; hold on;
set(gcf,'units','centimeters','position',[30 23 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.58 0.56 saxWidth*0.825 saxHeight*0.75]);
for idx = find(idx2use)
    idxcmap = round(rDist(idx));
    plot(usfptv(xUse),smoothsmooth(kafpca(xUse,idx),20),'color',cmap(idxcmap,:),'linewidth',0.2);
end
xlim([setBackY(2) xLim(2)]);
% ylim([setBackX(2) yLim(2)]);
line(setBackY([1,1]),yLim,'color','k','linewidth',lineWidth);
line(xLim,setBackX([1,1]),'color','k','linewidth',lineWidth);
xticks = 99:104;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt-100),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(101.5, setBackX(4), 'Time (ms)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:10:20;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
end
text(setBackY(4), mean(yLim), '\propto dF/dt (AU)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6 - figure supplement 1H
ddCoeff23 = [rDist(idx2use)' ones(sum(idx2use),1)] \ (dpkTimes(idx2use))';
xLim = [0 125];
yLim = [0 1.75];
setBackX = [-0.07 -0.12 -0.11 -0.27]/2*diff(yLim) + yLim(1);
setBackY = [-0.013 -0.022 -0.026 -0.0775]/0.45*diff(xLim) + xLim(1);
figure(8); clf; hold on;
set(gcf,'units','centimeters','position',[35 23 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.7 0.56 saxWidth*0.8 saxHeight*0.75]);
for idx = find(idx2use)
    idxcmap = round(rDist(idx));
    plot(rDist(idx), dpkTimes(idx)-100, 'linestyle','none','marker','.','color',cmap(idxcmap,:),'markersize',markerSize); 
end
line(xLim,ddCoeff23(1)*xLim + ddCoeff23(2)-100,'color','k','linewidth',lineWidth);
text(1,1.6,sprintf('%.1f µm/ms',round(1000/ddCoeff23(1))/1000),'fontsize',fontSize,'HorizontalAlignment','Left');
% Create Color Legend for Distance
dlegx = 0:5:125;
ycoord = [0 1 1 0]*0.075; 
for dx = 1:length(dlegx)-1
    patch(dlegx([dx,dx,dx+1,dx+1]),ycoord,cmap(dlegx(dx)+1,:),'EdgeColor','none');
end
xlim([setBackY(2) xLim(2)]);
ylim([setBackX(2) yLim(2)]);
line(setBackY([1,1]),yLim,'color','k','linewidth',lineWidth);
line(xLim,setBackX([1,1]),'color','k','linewidth',lineWidth);
xticks = 0:50:100;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(62.5, setBackX(4), 'Distance (µm)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.5:1.5;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), mean(yLim), 'Conduction Delay (ms)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');

fprintf('Conduction Velocity = %.1f µm/ms\n',1/ddCoeff23(1));
fprintf('AP Width = %.2f ms\n',mean(fwhmAp(idxKinkGood)));
fprintf('AP Spread = %.2f µm\n', mean(fwhmAp(idxKinkGood))/ddCoeff23(1));


% Figure 6 - figure supplement 1I
xLim = [99 104];
yLim = [-88 45];
setBackX = [-0.07 -0.12 -0.11 -0.27]/2*diff(yLim) + yLim(1);
setBackY = [-0.013 -0.022 -0.026 -0.0825]/0.45*diff(xLim) + xLim(1);
xUse = find(pstv>=xLim(1)+0.1,1):find(pstv>=xLim(2),1);
figure(10); clf; hold on; 
set(gcf,'units','centimeters','position',[40 23 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.75 0.56 saxWidth*0.75 saxHeight*0.82]);
plot(pstv(xUse),kinkAdjustedPhys(xUse,idxKinkGood),'color',0.2*[1,1,1],'linewidth',lineWidth)
line(xLim,apBottom*[1,1],'color','k','linewidth',lineWidth,'linestyle',':');
xlim([setBackY(2) xLim(2)]);
ylim([setBackX(2) yLim(2)]);
line(setBackY([1,1]),yLim,'color','k','linewidth',lineWidth);
line(xLim,setBackX([1,1]),'color','k','linewidth',lineWidth);
xticks = 99:104;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt-100),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(101.5, setBackX(4), 'Time (ms)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = -80:40:40;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), -20, 'Voltage (mV)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 6 - figure supplement 1J
xLim = [0 2.1];
yLim = [0 15];
setBackX = [-0.07 -0.12 -0.11 -0.27]/2*diff(yLim);
setBackY = [-0.013 -0.022 -0.026 -0.065]/0.45*diff(xLim);
figure(11); clf; hold on; 
set(gcf,'units','centimeters','position',[50 23 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.58 0.56 saxWidth*0.825 saxHeight*0.75]);
histogram(fwhmAp(idxKinkGood),8,'FaceColor','k','EdgeColor','none')
line(mean(fwhmAp(idxKinkGood))*[1,1],ylim,'color','k','linewidth',lineWidth);
text(mean(fwhmAp(idxKinkGood))+0.04,14,sprintf('mean = %.2f ms',mean(fwhmAp(idxKinkGood))),'Fontsize',fontSize,'HorizontalAlignment','Left');
xlim([setBackY(2) xLim(2)]);
ylim([setBackX(2) yLim(2)]);
line(setBackY([1,1]),yLim,'color','k','linewidth',lineWidth);
line(xLim,setBackX([1,1]),'color','k','linewidth',lineWidth);
xticks = 0:0.2:2.2;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    if xt==round(xt)
        text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
    end
end
text(1.05, setBackX(4), 'AP Width (ms)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:5:15;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), 7.5, 'Counts','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');





